<?php
class Country_NewsController extends Core_Controller_Action_Standard {
  private $_country = null;	
  public function init()
  {
    // Get viewer
    
    $country_id = $this->_getParam('country', 0);
    if($country_id){
    	$this->view->country = $this->_country = Engine_Api::_()->getItem('country', $country_id);
    }	
  }	
public function createAction()
  {
  	$viewer = Engine_Api::_()->user()->getViewer();
  	if(!$viewer->getIdentity()){
  		return $this->_forward('requireauth', 'error', 'core');
  	} 
  	
  	$this->view->country = $country = $this->_country;
	if(!$country || !$country->getIdentity()){
		return $this->_forward('requireauth', 'error', 'core');
	}
	//check permission
		
//	$this->view->tinyMce()->setOptions(Engine_Api::_()->country()->initTinyMCE());
    // Prepare form
    $this->view->form = $form = new Country_Form_News_Create();
            
    // If not post or form not valid, return
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }


    // Process
    $table = Engine_Api::_()->getItemTable('country_news');
    $db = $table->getAdapter();
    $db->beginTransaction();
	$values = $form->getValues();
    try {
      // Create news
      $viewer = Engine_Api::_()->user()->getViewer();
      $values = array_merge($form->getValues(), array(
        'owner_type' => $viewer->getType(),
        'owner_id' => $viewer->getIdentity(),
      ));

      $news = $table->createRow();
      $news->setFromArray($values);
      $news->save();
	  $news->country_id = $country->getIdentity();
      $news->save();
      
     // Add photo
      if( !empty($values['photo']) ) {
        $news->setPhoto($form->photo);
      } 	
      // Auth
      $auth = Engine_Api::_()->authorization()->context;
      $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');

     // if( empty($values['auth_view']) ) {
        $values['auth_view'] = 'everyone';
      //}

      //if( empty($values['auth_comment']) ) {
        $values['auth_comment'] = 'everyone';
      //}

      $viewMax = array_search($values['auth_view'], $roles);
      $commentMax = array_search($values['auth_comment'], $roles);

      foreach( $roles as $i => $role ) {
        $auth->setAllowed($news, $role, 'view', ($i <= $viewMax));
        $auth->setAllowed($news, $role, 'comment', ($i <= $commentMax));
      }
      

      // Add activity only if news is published
      if( $values['draft'] == 0 ) {
//        $action = Engine_Api::_()->getDbtable('actions', 'activity')->addActivity($viewer, $news, 'news_new');

        // make sure action exists before attaching the news to the activity
//        if( $action ) {
//          Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $news);
//        }

      }


      // Commit
      $db->commit();
    }

    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }

    return $this->_helper->redirector->gotoRoute(array('action' => 'view', 'news'=> $news->getIdentity(), 'country' => $news->country_id));
  }
public function viewAction()
  {
    // Check permission
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->country = $country = $this->_country;
    $news = Engine_Api::_()->getItem('country_news', $this->_getParam('news'));
    if( $news ) {
      Engine_Api::_()->core()->setSubject($news);
    }

    if( !$this->_helper->requireSubject()->isValid() ) {
      return;
    }
    if( !$this->_helper->requireAuth()->setAuthParams($news, $viewer, 'view')->isValid() ) {
      return;
    }
    if( !$news || !$news->getIdentity() || 
        ($news->draft && !$news->isOwner($viewer)) ) {
      return $this->_helper->requireSubject->forward();
    }
    
    // Prepare data
    $newsTable = Engine_Api::_()->getDbtable('news', 'country');
    
    $this->view->news = $news;
    $this->view->owner = $owner = $news->getOwner();
    $this->view->viewer = $viewer;
    
    if( !$news->isOwner($viewer) ) {
      $newsTable->update(array(
        'view_count' => new Zend_Db_Expr('view_count + 1'),
      ), array(
        'news_id = ?' => $news->getIdentity(),
      ));
    }
    
    // Get tags
//    $this->view->newsTags = $news->tags()->getTagMaps();
    
    // Get category
    if( !empty($news->category_id) ) {
      $this->view->category = Engine_Api::_()->getDbtable('newscategories', 'country')
          ->find($news->category_id)->current();
    }
    $social_share_default_code = '<div class="addthis_toolbox addthis_default_style ">
		<a class="addthis_button_preferred_1"></a>
		<a class="addthis_button_preferred_2"></a>
		<a class="addthis_button_preferred_3"></a>
		<a class="addthis_button_preferred_4"></a>
		<a class="addthis_button_preferred_5"></a>
		<a class="addthis_button_compact"></a>
		<a class="addthis_counter addthis_bubble_style"></a>
		</div>
		<script type="text/javascript">
		var addthis_config = {
							services_compact: "facebook, twitter, linkedin, google, digg, more",
							services_exclude: "print, email"
		}
		</script>
		<script type="text/javascript" src="https://s7.addthis.com/js/250/addthis_widget.js"></script>';

    $settings = Engine_Api::_()->getApi('settings', 'core');

    //GET CODE FROM LAYOUT SETTING
    $this->view->code = $settings->getSetting('sitereview.code.share', $social_share_default_code);
    $this->view->canDelete = Engine_Api::_()->getDbTable('Managers', 'Country')->isManager($this->_country, $viewer->getIdentity());
//    // Render
//    $this->_helper->content
//        //->setNoRender()
//        ->setEnabled()
//        ;
  }
  public function listAction()
  {
    // Preload info
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();
//    $this->view->owner = $owner = Engine_Api::_()->getItem('user', $this->_getParam('user_id'));
//    Engine_Api::_()->core()->setSubject($owner);

//    if( !$this->_helper->requireSubject()->isValid() ) {
//      return;
//    }
    
    
    // Make form
    $form = new Country_Form_News_Search();
    $form->populate($this->getRequest()->getParams());
    $values = $form->getValues();
    $this->view->formValues = array_filter($form->getValues());
//    $values['user_id'] = $owner->getIdentity();

    // Prepare data
    $newsTable = Engine_Api::_()->getDbtable('news', 'country');
    $values['country']  = $this->_country->getIdentity();
    // Get paginator
    $this->view->paginator = $paginator = Engine_Api::_()->getItemTable('country_news')->getNewsPaginator($values);
    $items_per_page = 15;
    $paginator->setItemCountPerPage($items_per_page);
    $this->view->paginator = $paginator->setCurrentPageNumber( $values['page'] );

//    // Render
//    $this->_helper->content
//        //->setNoRender()
//        ->setEnabled()
//        ;
  }
public function deleteAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $news = Engine_Api::_()->getItem('country_news', $this->getRequest()->getParam('news_id'));
    //if( !$this->_helper->requireAuth()->setAuthParams($news, null, 'delete')->isValid()) return;
	$canDelete = Engine_Api::_()->getDbTable('Managers', 'Country')->isManager($this->_country, $viewer->getIdentity());
	if(!$canDelete){
		return $this->_forward('requireauth', 'error', 'core');
	}
    // In smoothbox
    $this->_helper->layout->setLayout('default-simple');

    $this->view->form = $form = new Country_Form_News_Delete();

    if( !$news ) {
      $this->view->status = false;
      $this->view->error = Zend_Registry::get('Zend_Translate')->_("news entry doesn't exist or not authorized to delete");
      return;
    }

    if( !$this->getRequest()->isPost() ) {
      $this->view->status = false;
      $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
      return;
    }

    $db = $news->getTable()->getAdapter();
    $db->beginTransaction();

    try {
      $news->delete();
      
      $db->commit();
    } catch( Exception $e ) {
      $db->rollBack();
      throw $e;
    }

    $this->view->status = true;
    $this->view->message = Zend_Registry::get('Zend_Translate')->_('Your news entry has been deleted.');
    return $this->_forward('success' ,'utility', 'core', array(
      'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'view', 'id' => $this->_getParam('country', 0)), 'country_general', true),
      'messages' => Array($this->view->message)
    ));
  }
}
